# plugs/links.py
#
#

""" link <item> to <otheritem> """

__copyright__ = 'this file is in the public domain'

from gozerbot.commands import cmnds
from gozerbot.redispatcher import rebefore
from gozerbot.plughelp import plughelp
from gozerbot.examples import examples
from gozerbot.pdol import Pdol
from gozerbot.datadir import datadir

plughelp.add('links', 'maintain links')

links = Pdol(datadir + '/links')

def handle_linksadd(bot, ievent, groups):
    """ links-add <item> = <otheritem> """
    try:
        (item, otheritem) = groups
    except ValueError:
        ievent.missing('<item> = <otheritem>')
        return
    links.add(item, otheritem)
    links.save()
    ievent.reply('%s link added' % otheritem)

rebefore.add(5, 'links-add (.*?) = (.*)', handle_linksadd, 'USER')
examples.add('links-add', 'links-add <from> = <to> .. add a link', \
'links-add mekker = miep bla')

def handle_linksdel(bot, ievent, groups):
    """ links-del <item> = <otheritem> """
    try:
        (item, linkto) = groups
    except ValueError:
        ievent.missing('<item> = <link>')
        return
    itemlist = links[item]
    if not itemlist:
        ievent.reply('no links available for %s' % item)
        return
    for i in range(len(itemlist)-1, -1, -1):
        if itemlist[i] == linkto:
            del itemlist[i]
            links.save()
            ievent.reply('%s deleted' % linkto)
            return
            
rebefore.add(5, 'links-del (.*?) = (.*)', handle_linksdel, ['LINKS', 'OPER'])
examples.add('links-del', 'links-del <from> = <to> .. delete a link', \
'links-del mekker = miep bla')

def handle_linkslist(bot, ievent):
    """ links-list <item> .. show link of <item> """
    if not ievent.rest:
        ievent.missing('<item>')
        return
    result = links[ievent.rest]
    if result:
        ievent.reply(str(result))
    else:
        ievent.reply('no links found for %s' % ievent.rest)

cmnds.add('links-list', handle_linkslist, 'USER')
examples.add('links-list', 'links-list <item> .. show link of <item>', \
'links-list mekker')
